package com.sid.oncf.services.impl;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.*;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import com.sid.oncf.dao.interfaces.IUserDao;
import com.sid.oncf.entity.Users;

public class UserDetailsServiceImpl implements UserDetailsService {
	
	@Autowired
	private IUserDao iUserDao;

	public UserDetails loadUserByUsername(String username)
			throws UsernameNotFoundException {
		
		Users user=iUserDao.findByUserName(username);
		
		if(user!=null){
			String password=user.getPassword();
			boolean enabled = true;
            boolean accountNonExpired = true;
            boolean credentialsNonExpired = true;
            boolean accountNonLocked = true;
            
            User userSecurity=new User(username,password,enabled,accountNonExpired,
            		                   credentialsNonExpired,accountNonLocked,getAuthorities(user.getRoles().getRole()));
            
            return userSecurity;
		}
		
		else{
        	throw new UsernameNotFoundException("utilisateur n'existe pas");
        }
	}
	
	@SuppressWarnings("deprecation")
	private Collection<GrantedAuthority> getAuthorities(String role){
		List<GrantedAuthority> listRoles=new ArrayList<GrantedAuthority>();
		listRoles.add(new GrantedAuthorityImpl(role));
		return listRoles;
	}

}
